#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Cache management utilities for the visualization engine
"""

import time
import hashlib
from typing import Dict, Any, Optional, Tuple
import json


class CacheManager:
    """缓存管理器"""
    
    def __init__(self, ttl: int = 3600):
        """
        初始化缓存管理器
        
        Args:
            ttl: 缓存生存时间（秒）
        """
        self.ttl = ttl
        self._cache: Dict[str, Tuple[Any, float]] = {}
    
    def _generate_key(self, *args, **kwargs) -> str:
        """生成缓存键"""
        key_data = {
            'args': args,
            'kwargs': kwargs
        }
        key_str = json.dumps(key_data, sort_keys=True, default=str)
        return hashlib.md5(key_str.encode()).hexdigest()
    
    def get(self, key: str) -> Optional[Any]:
        """获取缓存值"""
        if key in self._cache:
            value, timestamp = self._cache[key]
            if time.time() - timestamp < self.ttl:
                return value
            else:
                del self._cache[key]
        return None
    
    def set(self, key: str, value: Any) -> None:
        """设置缓存值"""
        self._cache[key] = (value, time.time())
    
    def clear(self) -> None:
        """清空缓存"""
        self._cache.clear()
    
    def get_cache_info(self) -> Dict[str, Any]:
        """获取缓存信息"""
        current_time = time.time()
        valid_count = 0
        expired_count = 0
        
        for _, (_, timestamp) in self._cache.items():
            if current_time - timestamp < self.ttl:
                valid_count += 1
            else:
                expired_count += 1
        
        return {
            "total_entries": len(self._cache),
            "valid_entries": valid_count,
            "expired_entries": expired_count,
            "ttl": self.ttl
        } 